//
//  NewFeatureViewController.swift
//  Weibo10
//
//  Created by mac on 16/8/14.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SnapKit

private let WBNewFeatureImageCount = 4
private let WBNewFeatureReuseIdentifier = "WBNewFeatureReuseIdentifier"

// MARK: - 控制器的入口
class NewFeatureViewController: UICollectionViewController {
    
    // 重写构造函数
    init() {
        
        // 创建布局的对象
        let layout = UICollectionViewFlowLayout()
        
        // layout布局cell的属性
        layout.itemSize = UIScreen.mainScreen().bounds.size
        // cell的间距
        layout.minimumInteritemSpacing = 0
        // 行间距
        layout.minimumLineSpacing = 0
        // 滚动方法
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        // 控制器默认就是有view的，且有大小
        
        // 调用父类的方法，用布局对象初始化view
        super.init(collectionViewLayout: layout)
        
        // 分页
        collectionView?.pagingEnabled = true
        // 弹簧效果
        collectionView?.bounces = false
        // 滚动指示器
        collectionView?.showsHorizontalScrollIndicator = false
    }
    
    // 必须实现的方法，view已经创建
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()

               self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: WBNewFeatureReuseIdentifier)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
       
    }
}


// MARK: - UICollectionViewDataSource
extension NewFeatureViewController {
//    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
//        
//        return 0
//    }


    // 返回图片的数量
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return WBNewFeatureImageCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WBNewFeatureReuseIdentifier, forIndexPath: indexPath) as! NewFeatureCell
    
        cell.imageIndex = indexPath.item
        
    
        return cell
    }
    
    
    // ScrollView停止滚动调用的方法
    override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        
        // 最后一页调用动画的方法
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        // 判断是不是最后一页
        if page != WBNewFeatureImageCount - 1 {
            return
        }
        
        // 根据组号和下标取Cell
        let cell = collectionView?.cellForItemAtIndexPath(NSIndexPath(forItem: page, inSection: 0)) as!
        NewFeatureCell
        
        // 显示动画
        cell.showButtonAnim()
    }
}

// MARK: - UICollectionViewDelegate
extension NewFeatureViewController {
    /*
    // Uncomment this method to specify if the specified item should be highlighted during tracking
    override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }
    */

    /*
    // Uncomment this method to specify if the specified item should be selected
    override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }
    */

    /*
    // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
    override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }

    override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
        return false
    }

    override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
    
    }
    */

}

// MARK: - 私有对象
private class NewFeatureCell: UICollectionViewCell {
    
    // MARK: -图像属性
    private var imageIndex: Int = 0 {
        didSet {
            iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
            
            // 隐藏按钮
            startButton.hidden = true
        }
    }
    
    // 懒加载属性和图像
    private lazy var iconView: UIImageView = UIImageView()
    private lazy var startButton: UIButton = UIButton(title: "开始体验", color: UIColor.whiteColor(), imageName: "new_feature_finish_button")
    
    // 重写init的方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
    }

    // 必须重写的方法
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 封装的子控件
    private func setupUI() {
        
        // 在swift中必须先添加子控件，才可以设置约束
        addSubview(iconView)
        addSubview(startButton)
        
        // 隐藏button，但不能单纯隐藏在这里
        startButton.hidden = true
        
        // 设置空间的位置
        iconView.frame = bounds
        
        startButton.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX)
            make.bottom.equalTo(self.snp_bottom).multipliedBy(0.7)
        }
        
        addSubview(iconView)
        addSubview(startButton)

        
        startButton.addTarget(self, action: "clickStartButton", forControlEvents: UIControlEvents.TouchUpInside)
       
    }
    
    // Button的监听方法
    @objc private func clickStartButton() {
        
        // 发送通知切换控制器
        NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVieControllerNotification, object: nil)
        
    }
    
    // 按钮显示动画
    private func showButtonAnim() {
        
        startButton.hidden = false
        
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        
        startButton.userInteractionEnabled = false
        
        UIView.animateWithDuration(1.6,    // 动画时间
            delay: 0,                      // 延长时间
            usingSpringWithDamping: 0.6,   // 弹力系数
            // 0~1,系数越小弹力越大
            initialSpringVelocity: 10,     // 初始速度，模拟重力加速度
            options: [], animations: { () -> Void in
                self.startButton.transform = CGAffineTransformIdentity
                // 恢复到初始状态
            }) { (_) -> Void in
                
                self.startButton.userInteractionEnabled = true
                // 允许用户交互
        }
    }

}

